package com.合并两个有序链表;

public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        ListNode result=null;
        result=(list1.val <= list2.val)?list1:list2;
        ListNode headresult=result;
        list1 = list1.next;
        list2 = list2.next;
        while(list1!=null&&list2!=null){
            if(list1.val<list2.val){
                result.next=list1;
                list1 = list1.next;
            }
            else{
                result.next=list2;
                list1 = list1.next;
            }
            
            
            result = result.next;
        }
        while(list1!=null){
            result.next=list1;
            list1 = list1.next;
            result = result.next;
        }
        while(list2!=null){
            result.next=list2;
            list2 = list2.next;
            result = result.next;
        }
        return headresult;
    }
    //有头结点的
    public ListNode Merge1(ListNode list1,ListNode list2) {
        ListNode result=new ListNode(0);
        ListNode head = result;
        while(list1!=null&&list2!=null){
            if(list1.val<list2.val){
                result.next=list1;
                list1 = list1.next;
            }
            else{
                result.next = list2;
                list2 = list2.next;
            }
            
            
            result = result.next;
        }
        while(list1!=null){
            result.next=list1;
            list1 = list1.next;
            result = result.next;
        }
        while(list2!=null){
            result.next=list2;
            list2 = list2.next;
            result = result.next;
        }
       head = head.next;
        return head;
    }
}
